package ru.spb.osll.myfit.client.widget;

import ru.spb.osll.myfit.client.dialog.ErrorDialog;
import ru.spb.osll.myfit.client.log.LogsService;
import ru.spb.osll.myfit.client.log.LogsServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.TextArea;

public class LogPanel extends TextArea {
  private final LogsServiceAsync m_logsService = GWT.create(LogsService.class);

  private Timer m_timer = null;
  private ErrorDialog m_errorDialog = new ErrorDialog();

  private String m_pagePath;
  private String m_pageId;

  private int m_position = 0;
  private int m_sizeCap;

  private int m_scrollPosition;

  public void setScrollPosition(int m_scrollPosition) {
    this.m_scrollPosition = m_scrollPosition;
  }

  public void scroll() {
    Timer timer = new Timer() {
      @Override
      public void run() {
        getElement().setScrollTop(m_scrollPosition);
      }
    };
    timer.schedule(20);
  }

  public LogPanel() {
    super();
    setReadOnly(true);

    m_logsService.getLogTransferSize(new AsyncCallback<Integer>() {
      @Override
      public void onFailure(Throwable caught) {
        m_errorDialog.setMessage(caught);
        m_errorDialog.center();
      }

      @Override
      public void onSuccess(Integer cap) {
        if (cap != null) {
          m_sizeCap = cap;
        }
      }
    });
  }

  private String trimText(String text) {
    int newStringCharacter = text.indexOf("\n");
    while (text.length() - newStringCharacter > m_sizeCap)
      newStringCharacter = text.indexOf("\n", newStringCharacter + 1);
    return text.substring(newStringCharacter + 1);
  }

  private void appendText(String text) {
    m_position += text.length();
    String newText = getText() + text;
    if (newText.length() > m_sizeCap)
      newText = trimText(newText);
    setText(newText);
    getElement().setScrollTop(getElement().getScrollHeight());
  }

  public void clearLog() {
    setText("");
    m_position = 0;
  }

  public void stopGettingLogs() {
    m_timer.cancel();
    m_timer.schedule(1000);
  }

  public void startGettingLogs(String pagePath, String pageId) {
    m_pagePath = pagePath;
    m_pageId = pageId;

    m_timer = new Timer() {
      @Override
      public void run() {
        getLog();
      }
    };
    m_timer.scheduleRepeating(1000);
  }

  private void getLog() {
    m_logsService.getLogs(m_pagePath, m_pageId, m_position, new AsyncCallback<String>() {
      @Override
      public void onFailure(Throwable throwable) {
        m_errorDialog.center();
      }

      @Override
      public void onSuccess(String s) {
        if (!s.equals("")) {
          appendText(s);
        }
      }
    });
  }
}
